// pages/basket/basket.js
var config = require("../../utils/config.js");
// const Big = require("../../utils/big.min.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopCartList: [],
    listInfo: [], //全部信息
    totalMoney: 0,
    allChecked: false,
    startX: 0, //开始坐标
    startY: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */

  onReady: function () {
    // this.loadBasketData();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // http.getCartCount();//重新计算购物车总数量
    this.loadBasketData();
  },

  loadBasketData() {
    wx.showLoading(); //加载购物车
    // let tel = getApp().globalData.userInfo.tel||{}
    wx.request({
      url: config.baseUrl + '/carts?tel=' + getApp().globalData.tel,
      method: 'GET',
      success: res => {
        this.setData({
          shopCartList: res.data,
        })
      },
      complete: () => {
        this.getListInfo();
        this.checkAllSelected(); //检查全选状态
        wx.hideLoading();
      }
    })
  },

  // 获取商品信息
  getListInfo() {
    let listInfo = [];
    for (let i = 0; i < this.data.shopCartList.length; i++) {
      wx.request({
        url: config.baseUrl + '/goods/' + this.data.shopCartList[i].goodId,
        method: 'GET',
        success: res => {
          res.data.number = this.data.shopCartList[i].number
          res.data.checked = this.data.shopCartList[i].checked
          listInfo.push(res.data)
        },
        fail: () => {
          this.setData({
            listInfo: []
          })
        },
        complete: () => {
          this.setData({
            listInfo: listInfo
          })
          this.calTotalPrice(); //计算总价
        }
      })
    }
  },

  /**
   * 全选
   */
  onSelAll: function () {
    var allChecked = this.data.allChecked;
    allChecked = !allChecked; //改变状态
    var shopCartList = this.data.shopCartList;
    // 遍历修改购物车所有商品的选中状态
    for (var i = 0; i < shopCartList.length; i++) {
      shopCartList[i].checked = allChecked;
      wx.request({
        url: config.baseUrl + '/carts/' + shopCartList[i].id,
        method: 'PUT',
        data: shopCartList[i]
      })
    }
    this.setData({
      allChecked: allChecked,
      shopCartList: shopCartList
    });
    this.checkAllSelected(); //检查全选状态
    this.onShow()
  },

  /**
   * 每一项的选择事件
   */
  onSelectedItem: function (e) {
    var scindex = e.currentTarget.dataset.scindex; //传入点击的那一项索引
    var shopCartList = this.data.shopCartList; // 获取购物车列表
    var checked = shopCartList[scindex].checked; // 获取当前商品的选中状态
    shopCartList[scindex].checked = !checked; // 改变状态
    this.setData({
      shopCartList: shopCartList
    });
    wx.request({
      url: config.baseUrl + '/carts/' + shopCartList[scindex].id,
      method: "PUT",
      data: this.data.shopCartList[scindex], //修改传入项的数据
      success: res => {
        this.getListInfo() //成功后刷新数据
        this.checkAllSelected(); //检查全选状态
      }
    })
  },

  /**
   * 检查全选状态
   */
  checkAllSelected: function () {
    var allChecked = true;
    var shopCartList = this.data.shopCartList;
    var flag = false;
    for (var i = 0; i < shopCartList.length; i++) {
      if (!shopCartList[i].checked) {
        allChecked = !allChecked;
        flag = true;
        break;
      }
      if (flag) {
        break;
      }
    }
    this.setData({
      allChecked: allChecked
    });
  },

  /**
   * 计算购物车总额
   */
  calTotalPrice: function () {
    var shopCartList = this.data.shopCartList;
    var listInfo = this.data.listInfo; //所有选中项
    var totalPrice = 0;
    for (let i = 0; i < shopCartList.length; i++) {
      if (shopCartList[i].checked) {
        // console.log(listInfo[i].number);
        totalPrice += (listInfo[i].number) * (listInfo[i].price);
      }
    }
    this.setData({
      totalMoney: totalPrice
    })
    // wx.showLoading();
    // wx.hideLoading()
  },

  /**
   * 减少数量
   */
  onCountMinus: function (e) {
    var scindex = e.currentTarget.dataset.scindex;
    var shopCartList = this.data.shopCartList;
    if (shopCartList[scindex].number > 1) {
      shopCartList[scindex].number--
      this.updateCount(shopCartList[scindex]);
    }
  },

  /**
   * 增加数量
   */
  onCountPlus: function (e) {
    var scindex = e.currentTarget.dataset.scindex;
    var shopCartList = this.data.shopCartList;
    shopCartList[scindex].number++
    this.updateCount(shopCartList[scindex]);
  },


  /**
   * 改变购物车数量接口
   */
  updateCount: function (goodInfo) {
    wx.request({
      url: config.baseUrl + '/carts/' + goodInfo.id,
      method: 'PUT',
      data: goodInfo,
      success: res => {
        this.getListInfo()
      }
    })
  },

  /**
   * 删除购物车商品
   */
  onDelBasket: function () {
    var shopCartList = this.data.shopCartList;
    var selectedIds = []; //选中的商品的id
    for (var i = 0; i < shopCartList.length; i++) {
      if (shopCartList[i].checked) {
        selectedIds.push(shopCartList[i].id);
      }
    }
    if (selectedIds.length == 0) {
      wx.showToast({
        title: '请选择商品',
        icon: "none"
      })
    } else {
      wx.showModal({
        title: '',
        content: '确认要删除选中的商品吗？',
        confirmColor: "#eb2444",
        success(res) {
          if (res.confirm) {
            wx.showLoading({
              mask: true
            });
            for (i = 0; i < selectedIds.length; i++) {
              wx.request({
                url: config.baseUrl + '/carts/' + selectedIds[i],
                method: 'DELETE',
                success: res => {}
              })
            }
          }
        },
        complete: () => {
          wx.hideLoading()
          this.setData({
            listInfo: []
          })
          this.onShow()
          // this.checkAllSelected(); //检查全选状态
        }
      })
    }
  },

})